package Test.PracticeCAS;


import java.util.concurrent.atomic.AtomicStampedReference;

public class DealABADemo {

    //原子变量 AtomicInteger
    public static AtomicStampedReference<Integer> a = new AtomicStampedReference<>(new Integer(1), 1);

    public static void main(String[] args) {

        Thread main = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "  " + a.getStamp());

                Integer expectR = a.getReference();
                Integer expectStamp = a.getStamp();

                Integer newP = expectR + 1;
                Integer newStamp = expectStamp + 1;


                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                boolean compareAndSet = a.compareAndSet(expectR, newP,expectStamp, newStamp);

                System.out.println(compareAndSet);
                System.out.println(a.getReference());
                System.out.println(a.getStamp());
            }
        });


        Thread ganrao = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                a.compareAndSet(a.getReference(), a.getReference() + 1, a.getStamp(), a.getStamp() + 1);

                System.out.println(a.getReference());
                System.out.println(a.getStamp());

                a.compareAndSet(a.getReference(), a.getReference() - 1, a.getStamp(), a.getStamp() + 1);

                System.out.println(a.getReference());
                System.out.println(a.getStamp());
            }
        });

        main.start();
        ganrao.start();
    }

}